<template>
  <div class="app-container">
    <cus-wraper>
      <cus-filter-wraper>
        <el-input v-model="listQuery.search" placeholder="请输入角色名称" style="width:200px" clearable></el-input>
        <el-select filterable v-model="listQuery.status" placeholder="请选择菜单状态">
          <el-option v-for="item in optionsStatus" :key="item.value" :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
        <el-button type="primary" @click="getList" icon="el-icon-search">搜索</el-button>
        <el-button type="primary" @click="handleCreate" icon="el-icon-plus">添加</el-button>
      </cus-filter-wraper>

      <div class="table-container">
        <el-table v-loading="listLoading" :data="list" size="mini" element-loading-text="Loading" fit border
                  highlight-current-row>
          <el-table-column label="ID" prop="role_id"></el-table-column>
          <el-table-column label="角色名称" prop="role_name"></el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              {{ scope.row.status === 1 ? '正常' : '' }}
              {{ scope.row.status === 2 ? '禁用' : '' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="add_time"></el-table-column>
          <el-table-column label="角色描述" prop="role_memo"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.perPage"
                        @pagination="getList"/>
      </div>

      <el-dialog v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogVisible" width="60%"
                 @close="handleDialogClose">
        <el-form ref="dataForm" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="角色名称:" prop="role_name">
            <el-input v-model="form.role_name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述:" prop="remarks">
            <el-input v-model="form.role_memo" type="textarea" :rows="3" maxlength="200"></el-input>
          </el-form-item>
          <el-form-item label="角色状态" prop="status">
            <el-select filterable v-model="form.status" class="filter-item" placeholder="请选择角色状态" style="width: 280px;"
                       clearable>
              <el-option v-for="item in menuStatus" :key="item.key" :label="item.display_name" :value="item.key"/>
            </el-select>
          </el-form-item>
          <el-form-item label="角色的权限" prop="status">
            <el-table
              :data="cachedataMenuList"
              style="width: 100%;margin-bottom: 20px;"
              row-key="menu_id"
              border
              default-expand-all
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
              <el-table-column prop="menu_name" label="菜单" width="120"></el-table-column>
              <el-table-column prop="permission_name" label="权限">
                <template slot-scope="scope">
                  <ul>
                    <li v-for="i in scope.row.permissions" :key="i.permission_id"
                        @click="cachedataChecked(i.permission_id)">
                      <img v-if="cachedataMenuListCList.indexOf(i.permission_id)>-1" src="@/assets/img/checked.png"
                           style="width: 15px;" alt="">
                      <img v-else src="@/assets/img/unchecked.png" style="width: 15px;" alt="">
                      <span>{{ i.permission_name }}</span>
                    </li>
                  </ul>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="角色的菜单" prop="status">
            <el-tree ref="tree" :data="getenuList" show-checkbox node-key="menu_id"
                     :default-checked-keys="form.menu_name" :props="defaultProps"></el-tree>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </el-dialog>
    </cus-wraper>
  </div>
</template>

<script>
import {getRolePage, saveOrUpdateRole, deleteRole, cachedataMenu, getMenu} from '@/api/system/role'

const menuStatus = [
  {key: '1', display_name: '显示'},
  {key: '2', display_name: '隐藏'}
]
export default {
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        search: undefined
      },
      showReviewer: false,
      form: {
        id: undefined, //主键ID
        role_name: undefined, //角色名称
        role_memo: undefined, //角色描述
        status: undefined, //角色描述
        permission_arr: [], //角色描述
        menu_arr: [], //角色描述
      },
      dialogVisible: false,
      dialogStatus: '',
      titleMap: {
        update: '编辑',
        create: '创建'
      },
      menuStatus,
      optionsStatus: [{value: undefined, label: '全部状态'}, {value: '1', label: '显示'}, {value: '2', label: '隐藏'}],
      cachedataMenuList: [],// 树形菜单
      cachedataMenuListCList: [],
      getenuList: [],
      rules: {
        role_name: [
          {required: true, message: '请输入角色名', trigger: 'blur'},
          {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        permission_arr: [
          {required: true, message: '请选择权限', trigger: 'blur'}
        ],
        menu_arr: [
          {required: true, message: '请选择菜单', trigger: 'blur'}
        ],
        remarks: [
          {max: 200, message: '长度最多200个字符', trigger: 'blur'}
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'menu_name'
      },
      defaultProps2: {
        children: 'children',
        label: 'menu_name'
      },

    }
  },
  created() {
    this.getList()
    this.cachedataMenu()
    this.getMenu()
  },
  methods: {
    getList() {
      this.listLoading = true;
      let urlData = '?';
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`
      }
      getRolePage(urlData).then(response => {
        this.list = response.data.list;
        this.total = response.data.meta.total;
        this.listLoading = false;
      })
    },
    cachedataChecked(id) {
      if (this.cachedataMenuListCList.includes(id)) {
        this.cachedataMenuListCList.splice(this.cachedataMenuListCList.indexOf(id), 1);
      } else {
        this.cachedataMenuListCList.push(id)
      }
    },
    cachedataMenu() {
      cachedataMenu().then(response => {
        this.cachedataMenuList = response.data
      })
    },
    getMenu() {
      getMenu().then(response => {
        this.getenuList = response.data
      })
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = 'create';
      this.dialogVisible = true;
    },
    handleUpdate(row) {
      this.form = Object.assign({}, row);
      this.form.isRelatedSysMenu = undefined;
      this.form.isRelatedSysUser = undefined;
      this.form.isRelatedWxAccount = undefined;
      this.dialogStatus = "update";
      this.dialogVisible = true;
    },
    handleDelete(row) {
      if (row.isRelatedSysUser === '1' || row.isRelatedSysMenu === '1' || row.isRelatedWxAccount === '1') {
        this.$message({message: '请先解除关联', type: 'warning'});
        return false
      }
      deleteRole(row.id).then(response => {
        if (response.code === 200) {
          this.getList();
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          });
        }
      });
    },
    submitForm() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          let res = this.$refs.tree.getCheckedNodes(false, true);
          let arr = ''
          res.forEach((item) => {
            arr += `${item.menu_id},`
          })
          this.form.menu_arr = arr.substring(0, arr.lastIndexOf(','))
          this.form.permission_arr = this.cachedataMenuListCList.toString()
          saveOrUpdateRole(this.form).then(response => {
            if (response.code === 200) {
              this.getList();
              this.$notify({
                type: 'success',
                message: '操作成功',
                position: 'bottom-right',
                showClose: false,
                duration: 3000
              });
              this.dialogVisible = false;
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              });
            }
          }).catch(() => {
          });
        }
      });
    },
    resetForm() {
      this.form = {
        id: undefined, //主键ID
        role_name: undefined, //角色名称
        role_memo: undefined, //角色描述
        status: undefined, //角色描述
        permission_arr: undefined, //角色描述
        menu_arr: undefined, //角色描述
      }
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs['dataForm']) {
        this.$refs['dataForm'].clearValidate(); // 清除整个表单的校验
      }
    }
  }
}
</script>
